<template>
  <!-- 外层容器，使用DetailBox组件包裹整个页面内容 -->
  <DetailBox :border="2" :marginHeight="0">
    <template #center>
      <!-- 内容区域，使用ContentBox组件包裹地图和其他内容 -->
      <ContentBox :border="3" :marginHeight="40">
        <template #center>
          <!-- 地图组件，用于显示3D地图 -->
          <MapView
              ref="mapEle"
              :config="mapConfig"
              @map-ready="onMapReady"
          />

          <!-- 顶部信息区域，显示航班、保障等信息 -->
          <div class="topContent">
            <TopBox v-for="(item,index) in topInfo" :key="'topIfo' + index" :info="item" :index/>
          </div>

          <!-- 底部操作区域，包含筛选、统计等功能 -->
          <div class="bottomContent">
            <BottomBox @emitClick="btnClick" :isScreen @update:isScreen="updateScreen"/>
          </div>

          <!-- 模态框，用于显示表格数据 -->
          <Modal :visible :width="1000" closeButton @update:visible="closeModal" :title>
            <ZTable
                class="classTable"
                :tableData="tableData"
                :tableDataHeader="tableDataHeader"
            >
            </ZTable>
          </Modal>

          <!-- 可移动面板，用于显示详细信息或操作 -->
          <MoveablePanel v-if="isShowPanel" :width="w" :height="h" :title :left :top @close="closePanel">

            <div v-if="contentType===14" style="position:relative;">
              <!-- 登出确认信息 -->
              确认是否登出！
              <el-button size="small" type="danger" style="position: absolute; right: 0;top: 30px;"
                         @click="logout">确认
              </el-button>
            </div>
          </MoveablePanel>
        </template>
      </ContentBox>
    </template>
  </DetailBox>
</template>

<script setup lang="ts">
import {ref, onBeforeUnmount, watch, onUnmounted} from 'vue';
import DetailBox from "@/views/components/DetailBox.vue";
import ContentBox from "@/views/components/ContentBox.vue";
import MapView from '@/views/components/MapView/index.vue';
import TopBox from "@/views/largeScreen/TopBox.vue";
import BottomBox from "@/views/largeScreen/bottomBox.vue";
import Modal from "@/views/components/Modal.vue";
import MoveablePanel from "@/views/components/MoveablePanel.vue";
import aDingwei2 from './svg/a-dingwei2.svg'
import cheliang from './svg/cheliang.svg'
import chose from './svg/chose.svg'
import ditu from './svg/ditu.svg'
import feiji from './svg/feiji.svg'
import area_line from './svg/area_line.svg'
import jia from './svg/jia.svg'
import jian from './svg/jian.svg'
import lifangti1 from './svg/lifangti1.svg'
import shangse from './svg/shangse.svg'
import shuaxin from './svg/shuaxin.svg'
import tingche from './svg/tingche.svg'
import tuichu from './svg/tuichu.svg'
import windows from './svg/windows.svg'
import ZTable from "@/views/components/table/ZTable/index.vue";
import {ElNotification} from 'element-plus'
import {logout} from '@/utils/router'
import {UseWebsocket} from '@/utils/useWebsocket'

// top 部分
const topInfo = ref([
  {
    name: '航班信息',
    list: [
      {key: '总量', value: 84},
      {key: '已离', value: 11},
      {key: '未到', value: 10},
      {key: '停场', value: 73},
    ],
  },
  {
    name: '保障信息',
    list: [
      {key: '总　量', value: '69'},
      {key: '已　加', value: '13'},
      {key: '未　到', value: '54'},
      {key: '待　加', value: '1'},
      {key: '加油中', value: '1'},
    ],
  },
  {
    name: '油单信息',
    list: [
      {key: '总数', value: '13'},
      {key: '国内', value: '13'},
      {key: '国际', value: '0'},
      {key: '离境', value: '0'},
    ],
  },
  {
    name: '已供油量',
    list: [
      {key: '立方数', value: '53767.000'},
      {key: '总顿数', value: '42.029'},
    ],
  },
  {
    name: '车辆信息',
    list: [
      {key: '总　数', value: '9'},
      {key: '在　线', value: '1'},
      {key: '保障中', value: '-780'},
    ],
  },
  {
    name: '油料参数',
    list: [
      {key: '发布时间', value: '2025-05-29 05:40:28'},
      {key: '化验单号', value: 'LXP-25008'},
      {key: '温　　度', value: '18℃'},
      {key: '密　　度', value: '0.7817g/cm³'},
    ],
  }
])


// top 部分 -- end


const mapEle = ref<HTMLElement>();
// 自定义地图配置
const mapConfig = ref({
  basemaps: [
    // {name: '天地图', type: 'tdt', layer: 'img_d', show: true},
    // 可以添加更多图层
  ],
  scene: {
    center: {lat: 31, lng: 117, alt: 2000, heading: 0, pitch: 0},
    shadows: false, // 是否启用日照阴影
    removeDblClick: true, // 是否移除Cesium默认的双击事件

    // 以下是Cesium.Viewer所支持的options【控件相关的写在另外的control属性中】
    sceneMode: 2, // 3等价于Cesium.SceneMode.SCENE3D,
    // 以下是Cesium.Scene对象相关参数
    showSun: false, // 是否显示太阳
    showMoon: false, // 是否显示月亮
    showSkyBox: false, // 是否显示天空盒
    showSkyAtmosphere: false, // 是否显示地球大气层外光圈
    fog: false, // 是否启用雾化效果
    fxaa: true, // 是否启用抗锯齿
    // 以下是Cesium.Globe对象相关参数
    globe: {
      depthTestAgainstTerrain: false, // 是否启用深度监测
      baseColor: "#3a384e", // 地球默认背景色
      showGroundAtmosphere: false, // 是否在地球上绘制的地面大气
      enableLighting: false // 是否显示昼夜区域
    },
    // 以下是Cesium.ScreenSpaceCameraController对象相关参数
    cameraController: {
      zoomFactor: 3.0, // 鼠标滚轮放大的步长参数
      minimumZoomDistance: 50, // 地球放大的最小值（以米为单位）
      maximumZoomDistance: 5000, // 地球缩小的最大值（以米为单位）
      enableRotate: true, // 2D和3D视图下，是否允许用户旋转相机
      enableTranslate: true, // 2D和哥伦布视图下，是否允许用户平移地图
      enableTilt: true, // 3D和哥伦布视图下，是否允许用户倾斜相机
      enableZoom: true, // 是否允许 用户放大和缩小视图
      enableCollisionDetection: true // 是否允许 地形相机的碰撞检测
    }
  },
  terrain: false,
  control: {
    // fullscreenButton: {style: {position: 'fixed', left: "10px", bottom: "0px"}}, // 全屏按钮
    contextmenu: {hasDefault: true}, // 右键菜单
    // sceneModePicker: true,
    // infoBox: true,
    // vrButton: true,
    // geocoder: { service: "gaode" },
    // baseLayerPicker: true,
    // clockAnimate: true, // 时钟动画控制(左下角)
    // timeline: true, // 是否显示时间线控件
    // compass: { style: { bottom: "10px", left: "5px" } },
    // zoom: {insertIndex: 1,},
    // distanceLegend: {style: {left: "10px", bottom: "27px"}},// 刻度尺
  }
});

const {mars3d, Cesium} = window;

const contentType = ref(0)


// 地图加载完成的回调
const onMapReady = (mapView: any) => {
  console.log('地图加载完成', mapView, mars3d);

  // const tileLayer = new mars3d.layer.XyzLayer({
  //   url: "https://data.mars3d.cn/tile/dizhiChina/{z}/{x}/{y}.png",
  //   minimumLevel: 0,
  //   maximumLevel: 10,
  //   rectangle: { xmin: 69.706929, xmax: 136.560941, ymin: 15.831038, ymax: 52.558005 },
  //   opacity: 0.7
  // })
  // mapView.addLayer(tileLayer)

  const tiles3dLayer = new mars3d.layer.TilesetLayer({
    name: "石化工厂",
    url: "https://data.mars3d.cn/3dtiles/max-shihua/tileset.json",
    position: {lng: 117, lat: 31},
    // alt: 200, heading: 100, pitch: -100
    maximumScreenSpaceError: 1,
    shadows: Cesium.ShadowMode.DISABLED,
    // 以下参数可以参考用于3dtiles总数据大，清晰度过高情况下进行性能优化。这不是一个通用的解决方案，但可以以此为参考。
    skipLevelOfDetail: true,
    loadSiblings: true,
    cullRequestsWhileMoving: true,
    cullRequestsWhileMovingMultiplier: 10,
    preferLeaves: true,
    preloadWhenHidden: true,
    enableDebugWireframe: true, // 是否可以进行三角网的切换显示
    // 以上为优化的参数

    // popup: "all",
    // highlight: {
    //   type: 'click', // 默认为鼠标移入高亮，也可以指定click单击高亮
    //   // outlineEffect: true, // 采用OutlineEffect方式来高亮
    //   color: "#00FF00",
    //   width: 6
    // },
  })
  mapView.addLayer(tiles3dLayer)

  const toolButton1 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "统计控制",
    icon: windows,
    click: (event) => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
      // console.log(event);
      contentType.value = 1
      let {clientX, clientY} = event;

      w.value = 200
      h.value = 400
      isShowPanel.value = true
      title.value = '统计控制'
      left.value = clientX - w.value - 40;
      top.value = clientY;
    }
  })
  const toolButton2 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "区域管理",
    icon: ditu,
    click: (event) => {
      contentType.value = 2
      let {clientX, clientY} = event;

      w.value = 200
      h.value = 400
      isShowPanel.value = true
      title.value = '区域管理'
      left.value = clientX - w.value - 40;
      top.value = clientY;
    }
  })
  const toolButton3 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "航空公司过滤",
    icon: chose,
    click: (event) => {
      contentType.value = 3
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
      let {clientX, clientY} = event;

      w.value = 200
      h.value = 400
      isShowPanel.value = true
      title.value = '航空公司过滤'
      left.value = clientX - w.value - 40;
      top.value = clientY;
    }
  })
  const toolButton4 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "机位快速定位",
    icon: tingche,
    click: (event) => {
      contentType.value = 4
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
      let {clientX, clientY} = event;

      w.value = 200
      h.value = 400
      isShowPanel.value = true
      title.value = '机位快速定位'
      left.value = clientX - w.value - 40;
      top.value = clientY;
    }
  })
  const toolButton5 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "地图航班筛选",
    icon: feiji,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton6 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "重置",
    icon: shuaxin,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton7 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "地图设备筛选",
    icon: cheliang,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
      visible.value = true
      title.value = "地图设备筛选"
    }
  })
  const toolButton8 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "放大",
    icon: jia,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton9 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "缩小",
    icon: jian,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton10 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "定位",
    icon: aDingwei2,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton11 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "切换底图",
    icon: lifangti1,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton12 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "区域告警",
    icon: area_line,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton13 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "油管控制",
    icon: shangse,
    click: () => {
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
    }
  })
  const toolButton14 = new mars3d.control.ToolButton({
    className: 'info_content_value_tool',
    title: "登出",
    icon: tuichu,
    click: (event) => {
      contentType.value = 14
      // 单击了 示例按钮chinese，回调中想干啥就干啥~"
      let {clientX, clientY} = event;

      w.value = 200
      h.value = 130
      isShowPanel.value = true
      title.value = '登出'
      left.value = clientX - w.value - 40;
      top.value = clientY - 100; // 由于太靠近底边了让出底边 -100
    }
  })
  mapView.addControl(toolButton1)
  mapView.addControl(toolButton2)
  mapView.addControl(toolButton3)
  mapView.addControl(toolButton4)
  mapView.addControl(toolButton5)
  mapView.addControl(toolButton6)
  mapView.addControl(toolButton7)
  mapView.addControl(toolButton8)
  mapView.addControl(toolButton9)
  mapView.addControl(toolButton10)
  mapView.addControl(toolButton11)
  mapView.addControl(toolButton12)
  mapView.addControl(toolButton13)
  mapView.addControl(toolButton14)
  // const toolButton4 = new mars3d.control.ToolButton({
  //   title: "示例按钮chinese",
  //   icon: "img/svg/chinese.svg",
  //   click: () => {
  //     // 单击了 示例按钮chinese，回调中想干啥就干啥~"
  //   }
  // })
  // mapView.addControl(toolButton4)


  // 可以绑定Popup弹窗，回调方法中任意处理
  tiles3dLayer.bindPopup(function (event) {
    const attr = event.graphic.attr
    // attr["视频"] = `<video src='http://data.mars3d.cn/file/video/lukou.mp4' controls autoplay style="width: 300px;" ></video>`;
    return mars3d.Util.getTemplateHtml({title: "石化工厂", template: "all", attr})
  })

  // 单击事件
  tiles3dLayer.on(mars3d.EventType.click, function (event) {
    console.log("单击了3dtiles图层", event)
  })


  // 加个标识
  const graphic = new mars3d.graphic.PointEntity({
    position: [117, 31.001, 1441],
    style: {
      color: "#ff0000",
      pixelSize: 10,
      outlineColor: "#ffffff",
      outlineWidth: 2
    },
    tooltip: "我是视角中心点"
    // flyTo: true
  })
  mapView.graphicLayer.addGraphic(graphic)
};

const isScreen = ref(false)

const updateScreen = (args) => {
  // 先做操作再更新值
  isScreen.value = args;
}

const btnClick = (s) => {

  // switch (s) {
  //   case 'screenChange':
  //     isScreen.value = !s.value
  //     break;
  // }
  console.log(s)
}

const visible = ref(false)
const isShowPanel = ref(false)

// 定义一个变量来保存事件监听器
let clickListener: EventListener | null = null;

watch(isShowPanel, (newValue) => {
  if (newValue) {
    // 当 isShowPanel 为 true 时，绑定点击事件监听器
    // 延迟绑定全局点击事件监听器
    setTimeout(() => {
      clickListener = (event: MouseEvent) => {
        // 检查点击是否发生在面板外部

        const panel = document.querySelector('.moveable-panel');
        if (panel && !panel.contains(event.target as Node)) {
          isShowPanel.value = false; // 关闭面板
        }
      };

      document.addEventListener('click', clickListener);
    }, 100); // 延迟100ms绑定事件监听器，避免立即触发

  } else {
    // 当 isShowPanel 为 false 时，移除事件监听器
    if (clickListener) {
      document.removeEventListener('click', clickListener);
      clickListener = null;
    }
  }
});

// 确保在组件销毁时移除事件监听器
onUnmounted(() => {
  if (clickListener) {
    document.removeEventListener('click', clickListener);
  }
});

const closePanel = () => {
  isShowPanel.value = false
}

const title: string = ref('地图设备筛选')

const w = ref(0)
const h = ref(0)
const left = ref(0)
const top = ref(0)

const closeModal = (t) => {
  visible.value = t
}

const tableData = ref([
  {
    id: 1,
    date: '2016-05-02',
    name: 'wangxiaohu',
  },
  {
    id: 2,
    date: '2016-05-04',
    name: 'wangxiaohu',
  },
])

const tableDataHeader = [
  {
    label: '车牌号',
    prop: 'name',
    width: 100,
  }, {
    label: '状态',
    prop: 'name',
    width: 100,
  }, {
    label: '任务号',
    prop: 'name',
    width: 100,
  }, {
    label: '航班号',
    prop: 'name',
    width: 100,
  }, {
    label: '驾驶员',
    prop: 'name',
    width: 100,
  }, {
    label: '时间',
    prop: 'name',
    width: 100,
  },
  {
    label: '操作',
    operate: true,
    prop: 'Operation',
    children: [
      {
        label: '编辑',
        prop: 'edit',
        method: 'editRow',
        type: 'primary'
      },
      {
        label: '查看详情',
        prop: 'Detail',
        method: 'detailRow',
        type: 'info'
      }
    ]
  }
]
// 定义一个 ref 来保存通知实例
const notificationInstance = ref(null);
// 异常消息提示开启框
const errorMsg = (title = '标题', message = '信息', duration = 0) => {
  notificationInstance.value = ElNotification({
    title,
    message,
    duration
  })
}

// 页面销毁时取消提示并销毁
onBeforeUnmount(() => {
  if (notificationInstance.value) {
    notificationInstance.value.close(); // 关闭通知
  }

  ws.dispose();
});

const WSPath = import.meta.env.DEV ? import.meta.env.VITE_DEV_SOCKET : window.Z_GLOBAL_CONFIG.VITE_PRO_SOCKET

const ws = new UseWebsocket(WSPath)

// 建立连接
ws.connectionSocket();

// 发送消息
ws.send({
  type: 'message',
  content: 'Hello, server!'
});

// 监听消息
ws.on('message', (data) => {
  console.log('Received message:', data);
  // 测试片段
  if (notificationInstance.value) {
    notificationInstance.value.close()
    notificationInstance.value = null
  }
  errorMsg('限高警告', `民航${new Date().valueOf()}车辆超出限高`)
// setInterval(()=>{errorMsg('限高警告', '民航XXX车辆超出限高', 2000)},  4000)
});

</script>

<style lang="scss" scoped>
.topContent {
  position: fixed;
  top: 0;
  padding: 30px 0 0 14px;
}


.bottomContent {
  position: fixed;
  bottom: 0;
  padding: 0 0 30px 14px;
}

.classTable {
  color: #fff;
  height: calc(100% - 30px);
  overflow-y: auto;
  padding: 0 10px;
}

</style>

<style>
.cesium-viewer-toolbar {
  width: 40px !important;
  top: auto !important;
  bottom: 0 !important;
  right: 62px !important;
}

.mar3d-toolButton {
  color: #5a66b6 !important;
  border-radius: 50% !important;
  margin: 8px 0 !important;
  width: 40px !important;
  height: 40px !important;
  background: #fff !important;
}

.mar3d-toolButton img {
  width: 26px !important;
  height: 26px !important;
  position: relative !important;
  top: 6px !important;
  left: 6px !important;
}

</style>